package me.zhengjie.modules.system.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.system.bo.*;
import okhttp3.*;
import org.apache.commons.collections4.CollectionUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cjl
 * @className BaiDuAiUtils
 * @description: TODO
 * @company: 上海明我信息技术有限公司
 * @date 2023年05月17日
 * @version: 1.0
 */
@Slf4j
public class BaiDuAiWenZiUtils {


        public static final String API_KEY = "FGwVXlRQaG09hcpjTtCoqavA";
        public static final String SECRET_KEY = "FvCrPQfBKvcD7MyOqAKgq4B7WZgRSinV";

        static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

        public static void main(String[] args) throws IOException {
            BaiDuV2Result ai = getAiV1("/Users/mingwork/Downloads/122.png");
            boolean empty = CollectionUtils.isEmpty(ai.getWords_result());
            System.out.println(empty);
        }



    public static BaiDuV2Result getAiV1(String filePath)throws IOException{
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(filePath,true));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String string=response.body().string();
        System.out.println(string);
        BaiDuV2Result jsonObject=JSONObject.parseObject(string, BaiDuV2Result.class);
        System.out.println("baiduV2,"+JSON.toJSONString(jsonObject));
        return jsonObject;
    }


        /**
         * 获取文件base64编码
         *
         * @param path      文件路径
         * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
         * @return base64编码信息，不带文件头
         * @throws IOException IO异常
         */
        static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
            byte[] b = Files.readAllBytes(Paths.get(path));
            String base64 = Base64.getEncoder().encodeToString(b);
            if (urlEncode) {
                base64 = URLEncoder.encode(base64, "utf-8");
            }
            return base64;
        }


        /**
         * 从用户的AK，SK生成鉴权签名（Access Token）
         *
         * @return 鉴权签名（Access Token）
         * @throws IOException IO异常
         */
        static String getAccessToken() throws IOException {
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                    + "&client_secret=" + SECRET_KEY);
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            return jsonObject.getString("access_token");
        }

}
